package com.yb.core.handler;

import com.yb.core.bean.Resp;
import com.yb.core.exception.YbBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(YbBusinessException.class)
    public Resp handle(YbBusinessException e){
        log.error("exception:{}",e);
        return Resp.error(e);
    }

    @ExceptionHandler(RuntimeException.class)
    public Resp handle(RuntimeException e){
        log.error("exception:{}",e);
        return Resp.error().msg(e.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Resp handle(MethodArgumentNotValidException e){
        log.error("exception:{}",e);
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return Resp.error().msg(message);
    }

}
